package com.wetech.demo.web3j.service;

import com.wetech.demo.web3j.contracts.fsrtoken.FSRToken;
import org.springframework.stereotype.Service;
import org.web3j.crypto.Credentials;
import org.web3j.protocol.Web3j;
import org.web3j.tx.gas.DefaultGasProvider;

import java.math.BigInteger;

@Service
public class TokenService {

    private final Web3j web3j;
    private final Credentials credentials;

    public TokenService(Web3j web3j, Credentials credentials) {
        this.web3j = web3j;
        this.credentials = credentials;
    }

    private FSRToken load(String contractAddress) {
        return FSRToken.load(contractAddress, web3j, credentials, new DefaultGasProvider());
    }

    public String deploy() throws Exception {
        FSRToken contract = FSRToken.deploy(web3j, credentials, new DefaultGasProvider()).send();
        return contract.getContractAddress();
    }

    public String mint(String contractAddress, String to, BigInteger amount) throws Exception {
        return load(contractAddress).mint(to, amount).send().getTransactionHash();
    }

    public String transfer(String contractAddress, String to, BigInteger amount) throws Exception {
        return load(contractAddress).transfer(to, amount).send().getTransactionHash();
    }

    public BigInteger balanceOf(String contractAddress, String address) throws Exception {
        return load(contractAddress).balanceOf(address).send();
    }

    public String approve(String contractAddress, String spender, BigInteger amount) throws Exception {
        return load(contractAddress).approve(spender, amount).send().getTransactionHash();
    }

    public String transferFrom(String contractAddress, String from, String to, BigInteger amount) throws Exception {
        return load(contractAddress).transferFrom(from, to, amount).send().getTransactionHash();
    }
}
